# -*- coding: utf-8 -*-
import random

import csv#csv包可以读写csv文件
#读取数据
with open('Prostate_Cancer.csv','r') as file:
    reader = csv.DictReader(file)
    datas = [row for row in reader]#推导
#    print(datas)
#    for row in reader:
#        print(row)

#分组:训练集 测试集
random.shuffle(datas)#将数据集打乱顺序，相当于洗牌
n = len(datas)//3 #整除，避免小数的出现
#2/3是训练集 1/3是测试集
test_set = datas[0:n]#第0个到第n个不包含第n个
train_set = datas[n:]#从n开始到最后
#print(test_set)


#KNN
#1.算距离(欧氏距离或马氏距离)
'''
算两个数据之间的距离(欧氏距离)
'''
def distance(d1,d2):
    res = 0#求和
    for key in("radius","texture","perimeter","area","smoothness","compactness","symmetry","fractal_dimension"):
        res+=(float(d1[key])-float(d2[key]))**2
    return res**0.5

K = 6
def knn(data):
   '''
       KNN算法过程：
       1.求距离
       2.排序——升序
       3.取前K个
       4.加权平均
   '''
   #1.求距离
   res = [
       {"result":train['diagnosis_result'],"distance":distance(data,train)}
       for train in train_set
   ]
   #简单的推导
#   print(res)
   #2.排序(sorted默认升序排列)
   res = sorted(res,key = lambda item:item['distance'])
   # print(res)
   
   #3.取前K个
   resK = res[0:K]
#   print(resK)
   #4.加权平均(离的近的权重高，离得远的权重低)
   result = {'B':0,'M':0}
   #算前K个的总距离
   sum_distance = 0
   for r in resK:
       sum_distance += r['distance']

   for r in resK:
       result[r['result']] += 1 - r['distance']/sum_distance
   if(result['B'] > result['M']):
       return 'B'
   else:
       return 'M'
#   print(result)
   print(data['diagnosis_result'])

#knn(test_set[0])

#测试阶段
correct = 0
for test in test_set:
    result = test['diagnosis_result']#真实结果
    result_predict = knn(test)
    
    if result == result_predict:
        correct += 1

#print(correct)
#print(len(test_set))
        
print("准确率:{:.2f}%".format(100*correct/len(test_set)))


   

   
   
        